package org.hncors.gnssparse;

import android.app.Activity;
import android.content.Context;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;


import com.southgnss.connect.TopDeviceManage;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class SettingPageDebugActivity extends Activity
        implements
        OnClickListener,
        SelectInputTemplateDialog.onCustomDialogInputListener {
    private static final int serial_data = 1;
    private ArrayList<String> mSerialListItem = new ArrayList<String>();
    private static final int list_max = 500;
    private boolean mbShowHex = false;
    private boolean mbStart = true;
    //S550所用主板
    private final int unknow_command_1 = 200;
    private final int unknow_command_2 = 201;
    private final int unknow_command_3 = 202;
    //方盒子
    private final int box_register = 203;

    //M8机子
    private final int unknow_command_5 = 205;
    private final int unknow_command_6 = 206;
    private final int unknow_command_7 = 207;
    private final int unknow_command_8 = 208;
    private final int unknow_command_9 = 209;
    private final int unknow_command_10 = 210;

    //add 20180514 cqb 蓝牙连接RTK 快捷命令
    private final int command_11 = 211;
    private final int command_12 = 212;
    private final int command_13 = 213;
    private final int command_14 = 214;
    private final int command_15 = 215;
    private final int command_16 = 216;
    private final int command_17 = 217;

    private final int unique_box_reigster = 500;

    LocationManager mLocationManager;
    ListView mSerialDataListView;
    SerialDataItemAdapter mAdapter;
    private EditText sendTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_setting_debug);

        // 初始化
        InitData();
        InitUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outBundle) {
        super.onSaveInstanceState(outBundle);

        outBundle.putBoolean("IsShowHex", mbShowHex);
        outBundle.putBoolean("IsShowStart", mbStart);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        mbShowHex = savedInstanceState.getBoolean("IsShowHex");
        mbStart = savedInstanceState.getBoolean("IsShowStart");

        UpdateUIShowHex(mbShowHex);
        UpdateUIShowStart(mbStart);
    }

    @Override
    public void onResume() {
        super.onResume();//3
    }

    @Override
    public void onPause() {
        super.onPause();//4
    }

    @Override
    public void finish() {
        TopDeviceManage.getInstance(null).UnReceiverListener();
        super.finish();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case serial_data:
                    PostDataToUI(msg.getData().getString("serial_data"));
                    break;
            }
        }
    };

    private void PostMessageData(String data) {
        Message msg = new Message();
        msg.what = serial_data;
        Bundle b = new Bundle();
        b.putString("serial_data", data);
        msg.setData(b);

        if (mHandler != null) mHandler.sendMessage(msg);
    }

    private void PostDataToUI(String data) {
        // 存储容器无效或者当前是关闭状态, 不处理
        if (mSerialListItem == null) return;

        synchronized (mSerialListItem) {
            if (mSerialListItem.size() > list_max) mSerialListItem.clear();
            mSerialListItem.add(data);
        }

        if (mAdapter != null) mAdapter.notifyDataSetChanged();
    }


    private void InitData() {
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            TopDeviceManage.getInstance(null).RegReceiverListener(new TopDeviceManage.ReceiverListener() {
                @Override
                public void OnReceiverCallBack(int nLength, byte[] data) {
                    if (!mbStart) {
                        return;
                    }

                    String strDebugString;
                    if (mbShowHex) {
                        strDebugString = getHexString(data, nLength);
                    } else {
                        strDebugString = new String(data, 0, nLength);
                    }

                    PostMessageData(strDebugString);
                }
            });
    }

    private void InitUI() {
        mSerialDataListView = (ListView) findViewById(R.id.listViewSerialData);
        mSerialDataListView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
        mAdapter = new SerialDataItemAdapter(this);
        mSerialDataListView.setAdapter(mAdapter);

        // 控件点击回调
        View isShowHexView = findViewById(R.id.layoutDebugIsShowHex);
        View startOrStopView = findViewById(R.id.layoutDebugIsStartOrStop);
        View saveView = findViewById(R.id.layoutDebugIsSave);
        View clearView = findViewById(R.id.layoutDebugClear);
        View sendviView = findViewById(R.id.buttonDebugSend);
        sendTextView = (EditText) findViewById(R.id.editTextDebug);
        if (isShowHexView != null) isShowHexView.setOnClickListener(this);
        if (startOrStopView != null) startOrStopView.setOnClickListener(this);
        if (saveView != null) saveView.setOnClickListener(this);
        if (clearView != null) clearView.setOnClickListener(this);
        if (sendviView != null) sendviView.setOnClickListener(this);

        UpdateUIShowHex(mbShowHex);
        UpdateUIShowStart(mbStart);
    }

    private void UpdateUIShowHex(boolean isHex) {
        TextView hexTitleTextView = (TextView) findViewById(R.id.textViewDebugHex);
        String title = getString(isHex == true ? R.string.setting_rtk_serial_debug_data_hex : R.string.setting_rtk_serial_debug_data_str);
        if (hexTitleTextView != null) hexTitleTextView.setText(title);
    }

    private void UpdateUIShowStart(boolean isStart) {
        ImageView img = (ImageView) findViewById(R.id.imageViewDebugStartOrStop);
        TextView titleView = (TextView) findViewById(R.id.textViewDebugStartOrStop);

        if (img == null || titleView == null) return;
        titleView.setText(isStart == false ? R.string.setting_rtk_serial_debug_data_start : R.string.setting_rtk_serial_debug_data_pause);
    }

    private void UpdateUISaveStart(boolean isStart) {
        ImageView img = (ImageView) findViewById(R.id.imageViewDebugSaveOrStop);
        TextView titleView = (TextView) findViewById(R.id.textViewDebugSaveOrStop);

        if (img == null || titleView == null) return;
        titleView.setText(isStart == false ? R.string.setting_rtk_serial_debug_data_save : R.string.setting_rtk_serial_debug_data_no_save);
    }

    private String getHexString(byte[] data, int nLength) {
        String strTemString = "";
        for (int i = 0; i < nLength; i++) {
            strTemString += String.format("%02X ", data[i]);
        }
        return strTemString;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.layoutDebugIsShowHex) {
            mbShowHex = !mbShowHex;
            UpdateUIShowHex(mbShowHex);
            if (mAdapter != null) mAdapter.notifyDataSetChanged();
        } else if (v.getId() == R.id.layoutDebugIsStartOrStop) {
            mbStart = !mbStart;
            UpdateUIShowStart(mbStart);
        } else if (v.getId() == R.id.layoutDebugIsSave) {
        } else if (v.getId() == R.id.layoutDebugClear) {
            synchronized (mSerialListItem) {
                mSerialListItem.clear();
            }
            if (mAdapter != null) mAdapter.notifyDataSetChanged();
        } else if (v.getId() == R.id.buttonDebugSend) {

            if (sendTextView != null) {
                String data = sendTextView.getText().toString();
//				String data = "43 30 36 37 03";
                TopDeviceManage.getInstance(null).SendCommand(data + "\r\n");
            }
        }
    }

    private class SerialDataItemAdapter extends BaseAdapter {
        private Context mContext;
        private LayoutInflater mLayoutInflater;

        public SerialDataItemAdapter(Context context) {
            mContext = context;
            mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return mSerialListItem.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null)
                convertView = mLayoutInflater.inflate(R.layout.layout_setting_debug_list_item, null);

            TextView infoTextView = (TextView) convertView.findViewById(R.id.textViewInfo);
            if (infoTextView != null) {
                String strData = new String();
                synchronized (mSerialListItem) {
                    if (position < mSerialListItem.size()) {
                        strData = mSerialListItem.get(position);
                        //if (strData.isEmpty() == false && mbShowHex == true) strData = getHexString(strData.getBytes());
                    }
                }

                infoTextView.setText(strData);
            }

            return convertView;
        }
    }

    @Override
    public void onCustomDialogInputListener(int uniqueIdentifier, String data) {
        if (uniqueIdentifier == unique_box_reigster && data != null) {
            data.replace(" ", "");
            String strCommand = "#sic,,set,device.regi," + data + "\r\n";
            TopDeviceManage.getInstance(null).SendCommand(strCommand);
        }
    }

}
